<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>
<body>
  <!-- 
    canvas动画性能好
    canvas动画原理
      清掉画布，然后绘制新的位置
    
    圆形的碰撞检测


   -->
  <canvas width="500" height="500"></canvas>
  <script>
    var canvas = document.querySelector('canvas')
    var ctx = canvas.getContext('2d')
    
    var ball = {
      x: 20,
      y: 20,
      sx: -5,
      sy: -2
    }

    
    function draw () {
      ctx.beginPath()
      ctx.fillStyle = 'black'
      ctx.arc(ball.x, ball.y, 15, 0, Math.PI * 2)
      ctx.fill()
      ctx.closePath()
    }

    draw()
    
    setInterval(function () {
      /* if (ball.x >= canvas.width - 15 || ball.x < 15) {
        ball.sx = -ball.sx
      }
      
      if (ball.y >= canvas.height - 15 || ball.y < 15) {
        ball.sy = -ball.sy
      } */


      if (ball.x >= canvas.width + 15) {
        ball.x = -15
      }

      if (ball.x < -15) {
        ball.x = canvas.width + 15
      }

      if (ball.y >= canvas.height + 15) {
        ball.y = -15
      }

      if (ball.y < -15) {
        ball.y = canvas.height + 15
      }


      /* if () {
        ball.sx = -ball.sx
      } */

      ball.x += ball.sx
      ball.y += ball.sy
      // ctx.clearRect(0, 0, canvas.width, canvas.height)

      ctx.beginPath()
      ctx.fillStyle = 'rgba(255, 255, 255, 0.3)'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.closePath()
      draw()
    }, 1000 / 60)
  </script>
</body>
</html>